package com.coder520.remoteservicestudy;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by huang on 2017/7/9.
 */

public class StudentManagerService extends Service {
    private static final String TAG = StudentManagerService.class.getSimpleName();
    private List<Student> mStudents = new ArrayList<>();
    private StudentManagerImpl mManagerImpl;

    @Override
    public void onCreate() {
        super.onCreate();
        mManagerImpl = new StudentManagerImpl();
    }

    private class StudentManagerImpl extends IStudentManager.Stub {
        @Override
        public int getStudentCount() throws RemoteException {
            return mStudents.size();
        }

        @Override
        public void addStudent(Student student) throws RemoteException {
            Log.d(TAG, "code520 .... addStudent called:" + student);
            mStudents.add(student);
        }

        @Override
        public void deleteStudent(int id) throws RemoteException {
            Log.d(TAG, "code520 .... deleteStudent called:" + id);
            Iterator<Student> students = mStudents.iterator();
            while(students.hasNext()) {
                Student student = students.next();
                if (student.getId() == id) {
                    students.remove();
                }
            }
        }

        @Override
        public List<Student> getAllStudent() throws RemoteException {
            return mStudents;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mManagerImpl;
    }
}
